<?php

class CustomersController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/sp';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            array(
                'application.filters.RequireLoginFilter',
            ),
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
             
               'users'=>array('@'),
            ),
         
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionAjaxView($id){
      
        $rs=$this->loadModel($id)->getAttributes();
        echo json_encode($rs);
        Yii::app()->end();
      
    }
    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new Customers;
        $model->latecharge=0.0;
        
        $model->discount=0.0;
        $model->emailstatement=1;
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        
        if (isset($_POST['Customers'])) {
            $model->attributes = $_POST['Customers'];
            if ($model->save()){
                
                $this->redirect(array('update', 'id' => $model->custno));
            }
                
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }
   
    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);
        
     
         $globalContacts = Locationcontacts::model()->findAll("locno='00000' and custno='$model->custno'");
        foreach ($globalContacts as $contact)
        {
            $data[$contact->email] = 'G: '.$contact->contact . ' - ' . $contact->email . ' - ' . $contact->jobtitle;
        }
        $presidentContract = Employees::model()->findByPk('1109');
        if ($presidentContract != null)
        {
            $data[$presidentContract->workemail] = 'Greg Cahoe' . ' - ' . $presidentContract->workemail;
        }

        if (empty($data))
            $data = array('N/A', 'N/A');
        outputJsByList($data, 'contacts');

       
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        
        if (isset($_POST['Customers'])) {
      
                if(isset($_POST['Customers']['custno'])) unset($_POST['Customers']['custno']);
                if(isset($_POST['Customers']['salesperson'])) unset($_POST['Customers']['salesperson']);
                $model->attributes = $_POST['Customers'];                               
                $model->save();                             
        }
        
        $this->render('update', array(
            'model' => $model,
        ));
    }


   
    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }
   
    /**
     * Lists all models.
     */
    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('Customers');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new Customers('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Customers']))
            $model->attributes = $_GET['Customers'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = Customers::model()->findByPk($id);
        SalesPortalLoginCheckerUtil::canUserAccessCustomer($model);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'customers-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    
    /*
     * Param: query, page, sort, dir
     * Get customer list
     * return json array totalCount and array of customer
     */
    public function actionGetCustomerList($query=null , $page=1,$sort=NULL,$dir=NULL){
        //we decrease $page by 1 because in Extjs first page is 1, but in our sql first page is 0;
        if($page>0)$page--;

        $empno = $_GET['empno'];
        $crit = new CDbCriteria();
        
        $order = CJSON::decode($sort);
        if ($order != NULL)
        {
            $crit->order = $order[0]['property'] . ' ' . $order[0]['direction'];
        }
        else
        {
            $crit->order = 'custno';
        }

        if ($query != NULL)
        {
            $crit->compare('custno', $query, true);
            $crit->compare('lastname', $query, true, 'or');
            $crit->compare('add1', $query, true, 'or');
            $crit->compare('city', $query, false, 'or');
        }

        $crit->compare('salesperson',$empno);        

        $customers= new CActiveDataProvider('Customers',array(
            
            'criteria'=>$crit,
            'pagination'=>array(
                'pageSize'=>20,
                'currentPage'=>$page,
            ),
        ));


        
        $rs=array();
        if($customers->getTotalItemCount()>0){
            $rs['totalCount']=$customers->getTotalItemCount();
            $rs['type']='Customers';
            foreach($customers->getData() as $item){
                $rs['data'][]=$item->getAttributes();
                
            }
            echo json_encode($rs);
        }
        Yii::app()->end();
        
    }
    public function actionGetCustomer($query){
        $customer=Customers::model()->find('id=:id',array('id'=>$query));
        $rs=$customer->getAttributes();
        echo json_encode($rs);
        Yii::app()->end();
    }
    
    public function actionPopupCreateCustomer(){
        $this->layout='popup';
        $model = new Customers;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        
        if (isset($_POST['Customers'])) {
            $model->attributes = $_POST['Customers'];
            if ($model->save()){
                
                $this->redirect(array('view', 'id' => $model->custno));
            }
                
        }
        $this->render('popupCreateCustomer',array(
            'model'=>$model,
        ));
    }
}
